import { createRouter, createWebHashHistory, createWebHistory } from "vue-router";
import { staticRouter, errorRouter } from "@/routers/modules/staticRouter";
import useMenuStore from "@/stores/modules/menu";
import useUserStore from "@/stores/modules/user";
import { ROUTER_WHITE_LIST } from "@/config";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { ElMessage } from "element-plus";
import { safeT } from "@/locales/index";

type RouterMode = "hash" | "history";
const mode = (import.meta.env.VITE_ROUTER_MODE || "hash") as RouterMode;

// 路由模式映射
const routerMode = {
  hash: () => createWebHashHistory(),
  history: () => createWebHistory()
};

// 初始化路由
const router = createRouter({
  history: routerMode[mode](),
  routes: [...staticRouter, ...errorRouter],
  strict: false,
  scrollBehavior: () => ({ left: 0, top: 0 })
});

// 配置NProgress
NProgress.configure({
  showSpinner: false,
  speed: 500
});

/**
 * @description 路由拦截 beforeEach
 * */
router.beforeEach(async (to, from, next) => {
  NProgress.start();
  const menuStore = useMenuStore();
  const userStore = useUserStore();

  try {
    const title = import.meta.env.VITE_GLOB_SYSTEM_TITLE;
    document.title = to.meta.title ? `${to.meta.title} - ${title}` : title;

    if (to.path.toLocaleLowerCase() === "/login") {
      // token存在时，不跳转，不存在跳转登录页
      if (userStore.token) return next(from.fullPath);
      userStore.clearUserInfo();
      menuStore.resetDynamicRoutes();
      return next();
    } else if (ROUTER_WHITE_LIST.includes(to.path)) {
      // 白名单直接放行
      return next();
    } else if (!userStore.token) {
      // 重定向到 login 页面
      return next({ path: "/login", replace: true });
    }

    // 判断是否需要刷新路由
    if (!menuStore.topMenuList.length) {
      try {
        const hasMenus: boolean = await menuStore.getAllMenuTree("refresh");
        if (!hasMenus) {
          ElMessage({
            message: "获取菜单失败或无菜单权限", // 更清晰的提示
            type: "warning"
          });
          userStore.clearUserInfo();
          return next({ path: "/login", replace: true });
        }
        // 如果有菜单（无论是动态还是静态），则进行路由处理
        menuStore.addRouters();
        // 检查当前路由是否在新的菜单列表中
        const isRouteInMenu = menuStore.sidebarMenuList.some(r => r.path === to.path);
        const firstValidPath = menuStore.sidebarMenuList[0]?.path;
        console.log("firstValidPath", firstValidPath, to.path);

        if (!isRouteInMenu && firstValidPath) {
          // 如果当前路由无效，则重定向到第一个有效路由
          return next({ path: firstValidPath, replace: true });
        }
      } catch (_) {
        next("/500");
      } finally {
        NProgress.done();
      }
    }
    next();
  } catch (_) {
    next("/500");
  } finally {
    NProgress.done();
  }
});

/**
 * @description 路由跳转结束
 * */
router.afterEach(() => {
  NProgress.done();
});

/**
 * @description 路由错误处理
 */
router.onError(error => {
  NProgress.done();
  console.error("路由错误:", error);
});

export default router;
